package com.allwees.bs.c.module.security;

import com.alibaba.fastjson.JSON;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.vo.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 获取header中的jwt并校验其有效性
 * @author Daniel
 * @version 1.0.0
 * @since 2020/11/26 13:59
 */
@Slf4j
public class JwtTokenRequestFilter extends OncePerRequestFilter {

    private JwtTokenHelper jwtTokenHelper;

    private JwtTokenConfig jwtTokenConfig;

    public JwtTokenRequestFilter(JwtTokenHelper jwtTokenHelper, JwtTokenConfig jwtTokenConfig) {
        this.jwtTokenHelper = jwtTokenHelper;
        this.jwtTokenConfig = jwtTokenConfig;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String authHeader = request.getHeader(jwtTokenConfig.getHeader());
        String tokenPrefix = jwtTokenConfig.getPrefix();
        if (StringUtils.startsWithIgnoreCase(authHeader, tokenPrefix)) {
            String authToken = authHeader.substring(tokenPrefix.length());
            Claims claims;
            try {
                claims = jwtTokenHelper.parseClaims(authToken);
            } catch (ExpiredJwtException e) {
                ResponsePrinter.write(response, JSON.toJSONString(tokenInvalid()));
                return;
            }

            String username = Optional.ofNullable(claims).map(Claims::getSubject).orElse(null);
            log.info("===>checking authentication:username:{}", username);
            SecurityContext securityContext = SecurityContextHolder.getContext();
            if (username != null && securityContext.getAuthentication() == null) {
                //校验token是否有效(可以做一个自动续签的逻辑)
                if (jwtTokenHelper.isTokenInvalid(claims)) {
                    ResponsePrinter.write(response, JSON.toJSONString(tokenInvalid()));
                    return;
                }

//                UserDetails userDetails;
//                try {
//                    userDetails = this.userDetailsService.loadUserByUsername(username);
//                } catch (BaseException e) {
//                    R error = R.error(e.getCode(),e.getMsg());
//                    ResponsePrinter.write(response, JSON.toJSONString(error));
//                    return;
//                }
//                LiteDeviceResolver liteDeviceResolver = new LiteDeviceResolver();
//                Device device = liteDeviceResolver.resolveDevice(request);
                //UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                log.info("===>authenticated user:{},setting security context", username);
                securityContext.setAuthentication(jwtTokenHelper.genFromClaims(claims));
            }
        }
        chain.doFilter(request, response);
    }

    private R tokenInvalid(){
        return R.error(ResultEnum.INVALID_TOKEN);
    }
}
